<template>
    <div v-clickOutSide="() => (visible = false)">
        <a-dropdown :trigger="['click']" :visible="visible" :class="visible ? 'active' : ''" :getPopupContainer="(node) => node.parentNode">
            <flexbox class="ant-dropdown-link dropdown-wrap" @click.stop="visible = !visible">
                <span class="title-cont">
                    {{ showTitle }}
                </span>
                <DownOutlined style="margin-left: 4px" />
            </flexbox>
            <template #overlay>
                <div class="dropdown-body" v-empty="!isEmpty">
                    <a-input-search v-model:value="searchKeyword" placeholder="请输入" style="height: 26px" v-if="!isEmpty" />
                    <div style="padding: 8px 0 5px 0">
                        <a class="clear-text" v-if="!isEmpty" @click="handleClearAll">清除选择的内容</a>
                    </div>
                    <div style="max-height: 200px; overflow-y: auto">
                        <flexbox v-for="(item, index) of options" :key="item.id" :class="index === 0 ? '' : 'margin-t-8'">
                            <a-checkbox v-model:checked="item.checked" v-fitText @change="handleCheckChange">
                                {{ item.name }}
                            </a-checkbox>
                        </flexbox>
                    </div>
                </div>
            </template>
        </a-dropdown>
    </div>
</template>
<script lang="ts">
import api from '@/api';
import { debounce } from '@/utils/util';
import { DownOutlined } from '@ant-design/icons-vue';
import { defineComponent, reactive, toRefs, computed, watch } from 'vue';
export default defineComponent({
    components: {
        DownOutlined
    },
    props: {
        max: {
            type: Number,
            default: 2
        },
        searchQuery: {
            type: Object,
            default: () => ({})
        }, //额外的查询参数
        disabled: {
            type: Boolean,
            default: true
        }
    },
    emits: ['update:value'],
    setup(props, { attrs, emit }) {
        const state = reactive<any>({
            searchKeyword: '',
            options: [],
            selectedKeys: [],
            title: '标签',
            visible: false,
            isEmpty: true
        });
        const showTitle = computed(() => {
            const targetArr = state.selectedKeys.map((item) => item.name);
            if (targetArr.length) {
                return `标签：${targetArr.join(',')}`;
            } else {
                return `标签：${state.options.length ? '全部' : ''}`;
            }
        });
        const getOptions = async () => {
            const query = {
                ...props.searchQuery,
                name: state.searchKeyword
            };
            const { success, moule } = await api.labelModel.findLabelByName(query);
            if (success) {
                if (moule) {
                    state.options = moule.map((item) => {
                        const checked = state.selectedKeys.length ? state.selectedKeys.some((elem) => elem.id === item.id) : false;
                        return { ...item, checked };
                    });
                } else {
                    state.options = [];
                }
                state.isEmpty = moule ? !moule.length : true;
                if (state.options.length) {
                    if (!state.selectedKeys.length) {
                        const targetIds = state.options.map((item: Recordable) => ({
                            id: item.id
                        }));
                        emit('update:value', targetIds);
                    }
                } else {
                    emit('update:value', []);
                }
            }
        };
        const handleCheckChange = () => {
            const arr = state.options.filter((item) => item.checked);
            state.selectedKeys = [...arr];
            let targetIds = [];
            if (state.selectedKeys.length) {
                targetIds = state.selectedKeys.map((item: Recordable) => ({
                    id: item.id
                }));
            } else {
                targetIds = state.options.map((item: Recordable) => ({
                    id: item.id
                }));
            }
            emit('update:value', targetIds);
        };
        const handleClearAll = () => {
            state.selectedKeys = [];
            state.options = state.options.map((item) => ({
                ...item,
                checked: false
            }));
            emit('update:value', []);
        };
        const getDebounceOptions = debounce(getOptions, 300);
        watch(
            () => props.searchQuery,
            (n, o) => {
                // 如果最开始是禁用，则无需调用查询接口
                if (!attrs.disabled && JSON.stringify(n) !== JSON.stringify(o)) {
                    state.selectedKeys = [];
                    getDebounceOptions();
                }
            },
            {
                deep: true,
                immediate: true
            }
        );
        watch(
            () => state.searchKeyword,
            () => {
                getDebounceOptions();
            }
        );
        return {
            ...toRefs(state),
            showTitle,
            handleCheckChange,
            handleClearAll
        };
    }
});
</script>
<style lang="less" scoped>
@import './styles/index.less';
</style>
